package controllers

import play.api._
import data.Forms._
import i18n.Lang
import mvc.Results._
import play.api.mvc._
import play.api.data._
import models.ShopOwner
import views.html.helper.FieldConstructor
import views.html.fieldhelpers.defaultFieldConstructor
import play.mvc.Results.Todo

object Application extends Controller {
  implicit val lang: Lang = Lang("ru")
  val signUpForm = Form(
    tuple(
      "email" -> nonEmptyText,
      "password" -> nonEmptyText
    )
  )
  val loginForm = Form(
    tuple(
      "email" -> nonEmptyText,
      "password" -> nonEmptyText
    ) verifying ("Invalid email or password", result =>
      result match {
          case (email, password) =>
            ShopOwner.authenticate(email, password).isDefined
        }
      )
  )
  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }
  def getSignUp = Action {
    implicit request =>
      Ok(views.html.Application.signUp(signUpForm))
  }
  def postSignUp = Action {
    implicit request =>
      signUpForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.Application.signUp(formWithErrors)),
        user => {
          val (email, password) = user
          ShopOwner.create(ShopOwner(email, password, ""))
          Redirect(routes.Application.index()).withSession("email" -> email)
        }
      )

  }
  def getLogOn = Action {
    implicit request =>
      Ok(views.html.Application.logOn(loginForm))
  }
  def postLogOn = Action {
    implicit request =>
      loginForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.Application.logOn(formWithErrors)),
        user => {
          val (email, password) = user
          Redirect(routes.Application.index).withSession("email" -> email)
        }
      )
  }

}

object MyHelpers {
  implicit val myFields = FieldConstructor(defaultFieldConstructor.f)

}

trait Secured {

  /**
   * Retrieve the connected user email.
   */
  private def username(request: RequestHeader) = request.session.get("email")

  /**
   * Redirect to login if the user in not authorized.
   */
  private def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Application.getLogOn)

  // --

  /**
   * Action for authenticated users.
   */
  def IsAuthenticated(f: => String => Request[AnyContent] => Result) = Security.Authenticated(username, onUnauthorized) { user =>
    Action(request => f(user)(request))
  }

  /**
   * Check if the connected user is a member of this project.
   */
  def IsMemberOf(group: Long)(f: => String => Request[AnyContent] => Result) = IsAuthenticated { user => request =>
    Results.Forbidden
  }

  /**
   * Check if the connected user is a owner of this task.
   */
  def IsOwnerOf(shop: Long)(f: => String => Request[AnyContent] => Result) = IsAuthenticated { user => request =>
    Results.Forbidden
  }

}